package cloud.keveri.gateway.plugin.global;

import cloud.keveri.gateway.plugin.api.KeveriPluginChain;
import cloud.keveri.gateway.plugin.api.context.GatewayContext;
import cloud.keveri.gateway.plugin.api.context.GatewayContextBuilder;
import cloud.keveri.gateway.plugin.base.AbstractKeveriPlugin;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

import static cloud.keveri.gateway.plugin.base.def.Const.CONTEXT;
import static cloud.keveri.gateway.plugin.base.def.Const.PLUGIN_GLOBAL_ORDER;

/**
 * <p>
 * 作者：沈自在
 **/
public class GlobalPlugin extends AbstractKeveriPlugin {
    private final GatewayContextBuilder builder;

    public GlobalPlugin(GatewayContextBuilder builder) {
        this.builder = builder;
    }

    @Override
    public int getOrder() {
        return PLUGIN_GLOBAL_ORDER;
    }

    @Override
    protected Mono<Void> doExecute(ServerWebExchange exchange, KeveriPluginChain chain) {
        // 1. 构造 context
        GatewayContext context = builder.build(exchange);
        if (Objects.isNull(context)) return chain.execute(exchange);
        // 2. 存储
        exchange.getAttributes().put(CONTEXT, context);

        // 3. 放行
        return chain.execute(exchange);
    }
}
